﻿using Interface.Cache;
using Interface.Core.Controllers;
using Interface.Core.Utility;
using Interface.Mvc.Areas.Scrm.Models;
using Interface.Utility.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Interface.Mvc.Areas.Scrm.Controllers
{
    public class IntegralController : CoreController
    {
        private IEnumerable<MemberSource> Sources
        {
            get
            {
                return CommonCache.GetCache("Scrm_Member_Sources", () =>
                {
                    return db.Scrm.GetList<MemberSource>();
                });
            }
        }

        private bool RefCrmID(string mobile, int? memberid, ref int? crmid)
        {
            if (!crmid.HasValue || crmid == 0)
            {
                if (memberid.HasValue && memberid > 0)
                {
                    string sql = @"select t1.IntRelate from Member_Relate as t1
                        inner join Member_Source as t2 on t2.ID = t1.SourceID
                        where t2.Code = 'crm' and t1.MemberID = @MemberID";
                    crmid = db.Scrm.ExecuteScalar<int>(sql, new { MemberID = memberid });
                }
                if ((!crmid.HasValue || crmid == 0) && !string.IsNullOrEmpty(mobile))
                {
                    string sql = @"select t1.IntRelate from Member_Relate as t1 
                        inner join Member_Source as t2 on t2.ID = t1.SourceID
                        inner join Member_Info as t3 on t3.ID = t1.MemberID
                        where t2.Code = 'crm' and t3.Mobile = @Mobile";
                    crmid = db.Scrm.ExecuteScalar<int>(sql, new { Mobile = mobile });
                }
            }
            return crmid > 0;
        }

        /// <summary>
        /// 积分查询
        /// params: mobile,memberid,crmid
        /// </summary>
        [HttpGet]
        public string Query(string mobile, int? memberid, int? crmid)
        {
            if (!RefCrmID(mobile, memberid, ref crmid))
            {
                return ResultUtility.FailureResult("用户信息缺失!");
            }

            ResultEntity re = db.Crm.StoredQuery<ResultEntity>("Scrm_Sp_IntegralQuery", new
            {
                crmid = crmid
            }).FirstOrDefault();

            return ResultUtility.UnknownResult(re.success, re.imessage, re.imessage, re.data);
        }

        /// <summary>
        /// 积分明细
        /// params: mobile,memberid,crmid
        /// </summary>
        [HttpGet]
        public string Detail(string mobile, int? memberid, int? crmid)
        {
            if (!RefCrmID(mobile, memberid, ref crmid))
            {
                return ResultUtility.FailureResult("用户信息缺失!");
            }

            List<dynamic> list = db.Crm.StoredQuery<dynamic>("Scrm_Sp_IntegralDetail", new
            {
                crmid = crmid
            }).ToList();

            return ResultUtility.SuccessResult(data: list);
        }

        /// <summary>
        /// 增加积分
        /// params: mobile,memberid,crmid,amount
        /// </summary>
        [HttpPost]
        public string Augment(string mobile, int? memberid, int? crmid, int amount, string remark)
        {
            if (!RefCrmID(mobile, memberid, ref crmid))
            {
                return ResultUtility.FailureResult("用户信息缺失!");
            }

            ResultEntity re = db.Crm.StoredQuery<ResultEntity>("Scrm_Sp_IntegralAdjust", new
            {
                crmid = crmid,
                amount = amount,
                remark = remark
            }).FirstOrDefault();

            if (re.success && amount >= 50) // 积分增加达到50以上才发送模板消息
            {
                string sql = @"select t1.MemberID, t2.CharRelate from Member_Relate as t1
                    inner join Member_Relate as t2 on t1.MemberID = t2.MemberID
                    where t1.IntRelate = @crmid and t2.SourceID = @sourceid";
                int sourceid = Sources.FirstOrDefault(m => m.Code == "taste").ID;
                var list = db.Scrm.Query<dynamic>(sql, new { sourceid, crmid }).ToList();
                if (list.Count > 0)
                {
                    try
                    {
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        dic.Add("source", Sources.FirstOrDefault(m => m.Code == appid).Name);
                        dic.Add("scrmid", list.FirstOrDefault().MemberID);
                        dic.Add("openid", list.FirstOrDefault().CharRelate);
                        dic.Add("points", amount);
                        dic.Add("remark", remark);
                        HttpHelper.Post("https://www.uvmami.com/interface/pointschangetemplate?key=engnice", dic);
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            return ResultUtility.UnknownResult(re.success, re.imessage, re.imessage);
        }

        /// <summary>
        /// 减少积分
        /// params: mobile,memberid,crmid,amount
        /// </summary>
        [HttpPost]
        public string Lessen(string mobile, int? memberid, int? crmid, int amount, string remark)
        {
            if (!RefCrmID(mobile, memberid, ref crmid))
            {
                return ResultUtility.FailureResult("用户信息缺失!");
            }

            ResultEntity re = db.Crm.StoredQuery<ResultEntity>("Scrm_Sp_IntegralAdjust", new
            {
                crmid = crmid,
                amount = -amount,
                remark = remark
            }).FirstOrDefault();

            if (re.success && amount >= 50) // 积分减少达到50以上才发送模板消息
            {
                string sql = @"select t1.MemberID, t2.CharRelate from Member_Relate as t1
                    inner join Member_Relate as t2 on t1.MemberID = t2.MemberID
                    where t1.IntRelate = @crmid and t2.SourceID = @sourceid";
                int sourceid = Sources.FirstOrDefault(m => m.Code == "taste").ID;
                var list = db.Scrm.Query<dynamic>(sql, new { sourceid, crmid }).ToList();
                if (list.Count > 0)
                {
                    try
                    {
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        dic.Add("source", Sources.FirstOrDefault(m => m.Code == appid).Name);
                        dic.Add("scrmid", list.FirstOrDefault().MemberID);
                        dic.Add("openid", list.FirstOrDefault().CharRelate);
                        dic.Add("points", -amount);
                        dic.Add("remark", remark);
                        HttpHelper.Post("https://www.uvmami.com/interface/pointschangetemplate?key=engnice", dic);
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            return ResultUtility.UnknownResult(re.success, re.imessage, re.imessage);
        }

        /// <summary>
        /// 积分操作
        /// params: mobile,memberid,crmid,code
        /// </summary>
        [HttpPost]
        public string Integral(string mobile, int? memberid, int? crmid, string code)
        {
            if (!RefCrmID(mobile, memberid, ref crmid))
            {
                return ResultUtility.FailureResult("用户信息缺失!");
            }

            ResultEntity re = db.Crm.StoredQuery<ResultEntity>("Scrm_Sp_Integral", new
            {
                crmid = crmid,
                code = code
            }).FirstOrDefault();

            if (re.success)
            {
                string sql = @"select t1.MemberID, t2.CharRelate from Member_Relate as t1
                    inner join Member_Relate as t2 on t1.MemberID = t2.MemberID
                    where t1.IntRelate = @crmid and t2.SourceID = @sourceid";
                int sourceid = Sources.FirstOrDefault(m => m.Code == "taste").ID;
                var list = db.Scrm.Query<dynamic>(sql, new { sourceid, crmid }).ToList();
                if (list.Count > 0 && re.data != null)
                {
                    try
                    {
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        dic.Add("source", Sources.FirstOrDefault(m => m.Code == appid).Name);
                        dic.Add("scrmid", list.FirstOrDefault().MemberID);
                        dic.Add("openid", list.FirstOrDefault().CharRelate);
                        dic.Add("points", re.data);
                        dic.Add("remark", "产品积分获得微笑值");
                        HttpHelper.Post("https://www.uvmami.com/interface/pointschangetemplate?key=engnice", dic);
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            return ResultUtility.UnknownResult(re.success, re.imessage, re.imessage);
        }

        /// <summary>
        /// 新客有礼查询是否购买过
        /// url: /scrm/product/hasbuy
        /// params: mobile,memberid,crmid
        /// </summary>
        [HttpGet]
        public string HasBuy(string mobile, int? memberid, int? crmid)
        {
            if (!RefCrmID(mobile, memberid, ref crmid))
            {
                return ResultUtility.FailureResult("用户信息缺失!");
            }

            string sql = @"Select COUNT(1) From CRM_V_PNT_ClientPointsDetail(nolock) Where Product<>0 And Client=@CrmID";

            var hasbuy = db.Erp.Query<int>(sql, new { crmid }).FirstOrDefault() > 0;

            return ResultUtility.SuccessResult(data: hasbuy);
        }

        /// <summary>
        /// 新客有礼积分操作
        /// params: mobile,code,shopcode
        /// </summary>
        [HttpPost]
        public string NewGuestIntegral(string mobile, string code, string shopcode)
        {
            dynamic re = db.Erp.StoredQuery<dynamic>("Crm_Sp_MemberIntegration", new
            {
                oper_id = 1,
                mobile = mobile,
                mdcode = shopcode,
                markcode = code,
                activityid = 1151,
                ly = 7
            }).FirstOrDefault();

            return ResultUtility.UnknownResult(re.Success > 0, re.IMessage, re.IMessage);
        }

        /// <summary>
        /// 奥运助力积分操作
        /// params: mobile,memberid,crmid,code,shopcode
        /// </summary>
        [HttpPost]
        public string OlympicIntegral(string mobile, int? memberid, int? crmid, string code, string shopcode)
        {
            if (!RefCrmID(mobile, memberid, ref crmid))
            {
                return ResultUtility.FailureResult("用户信息缺失!");
            }

            ResultEntity re = db.Crm.StoredQuery<ResultEntity>("Scrm_Sp_OlympicIntegral", new
            {
                crmid = crmid,
                shopcode = shopcode,
                code = code
            }).FirstOrDefault();

            if (re.success)
            {
                string sql = @"select t1.MemberID, t2.CharRelate from Member_Relate as t1
                    inner join Member_Relate as t2 on t1.MemberID = t2.MemberID
                    where t1.IntRelate = @crmid and t2.SourceID = @sourceid";
                int sourceid = Sources.FirstOrDefault(m => m.Code == "taste").ID;
                var list = db.Scrm.Query<dynamic>(sql, new { sourceid, crmid }).ToList();
                if (list.Count > 0 && re.data != null)
                {
                    try
                    {
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        dic.Add("source", Sources.FirstOrDefault(m => m.Code == appid).Name);
                        dic.Add("scrmid", list.FirstOrDefault().MemberID);
                        dic.Add("openid", list.FirstOrDefault().CharRelate);
                        dic.Add("points", re.data);
                        dic.Add("remark", "产品积分获得微笑值");
                        HttpHelper.Post("https://www.uvmami.com/interface/pointschangetemplate?key=engnice", dic);
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            return ResultUtility.UnknownResult(re.success, re.imessage, re.imessage);
        }

        /// <summary>
        /// 奥运活动屏蔽积分码 临时使用
        /// url: /scrm/integral/olympicjfpb
        /// params: code
        /// </summary>
        [HttpPost]
        public string OlympicJfPb(string code)
        {
            var result = db.Crm.StoredQuery<ResultEntity>("Scrm_Sp_JfPb", new { Code = code }).FirstOrDefault();

            return ResultUtility.UnknownResult(result.success, result.imessage, result.imessage, result.data);
        }
    }
}